package com.example.administrator.smartbutler.ui;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.Toast;

import com.example.administrator.smartbutler.R;
import com.example.administrator.smartbutler.adapter.CourierAdapter;
import com.example.administrator.smartbutler.entity.CourierCompany;
import com.example.administrator.smartbutler.entity.CourierData;
import com.example.administrator.smartbutler.utils.L;
import com.example.administrator.smartbutler.utils.StaticClass;
import com.google.gson.JsonObject;
import com.kymjs.rxvolley.RxVolley;
import com.kymjs.rxvolley.client.HttpCallback;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;

/**
 * 项目名:SmartButler
 * 包名:com.example.administrator.smartbutler.ui
 * 文件名：CourierActivity
 * 创建者：justin
 * Created by Administrator on 2018/2/7.
 * 描述：TODO
 */

public class CourierActivity extends BaseActivity implements View.OnClickListener {

    private Spinner courier_company;


    private EditText courier_number;

    private Button courier_query;

    private ListView courier_listView;

    private List<CourierData> mList = new ArrayList<>();

    private CourierAdapter adapter;

    private String company;

    String[] arr = {};


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_courier);

        initView();


    }

    private void initView() {

        courier_company = (Spinner) findViewById(R.id.courier_company);

        courier_number = (EditText) findViewById(R.id.courier_number);

        courier_query = (Button) findViewById(R.id.courier_query);

        courier_listView = (ListView) findViewById(R.id.courier_listView);

        courier_query.setOnClickListener(this);


        BmobQuery<CourierCompany> query = new BmobQuery<>();

        query.findObjects(new FindListener<CourierCompany>() {
            @Override
            public void done(List<CourierCompany> list, BmobException e) {

                if (e == null) {

                    List<String> temp = new ArrayList<String>();

                    for (CourierCompany courierCompany : list) {
                        temp.add(courierCompany.getName());
                    }

                    arr = temp.toArray(new String[0]);
                }

            }
        });


        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, arr);

        L.i(arr.toString() + "------------");


        courier_company.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                company = arr[position];
                //设置显示当前选择的项
                parent.setVisibility(View.VISIBLE);

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        courier_company.setAdapter(adapter);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.courier_query:
                /**
                 * 1.获取输入框的内容
                 * 2.判断是否为空
                 * 3.拿到数据去请求数据（Json）
                 * 4.解析Json
                 * 5.listview适配器
                 * 6.实体类（item）
                 * 7.设置数据/显示效果
                 */


                String number = courier_number.getText().toString().trim();

                //拼接地址

//                String url = "http://v.juhe.cn/exp/index?key=" + StaticClass.COURIRE_KEY +
//                        "&com=" + company + "&no=" + number;

                String url = "http://api.jisuapi.com/express/query?appkey=" + StaticClass.JISUAPI_APPKEY +
                        "&type=auto" + "&number" + number;


                if (!TextUtils.isEmpty(company) & !TextUtils.isEmpty(number)) {

                    //用RxVolley来放松请求
                    RxVolley.get(url, new HttpCallback() {
                        @Override
                        public void onSuccess(String t) {
                            L.i("Courier:" + t);
                            parsingJSON(t);
                        }

                        @Override
                        public void onFailure(int errorNo, String strMsg) {
                            L.i("Courier:" + errorNo + "-" + strMsg);

                        }
                    });


                } else {

                    Toast.makeText(this, "输入框不能为空", Toast.LENGTH_SHORT).show();

                }


                break;
        }

    }


    private void parsingJSON(String t) {

        try {
            JSONObject jsonObject = new JSONObject(t);
            JSONObject jsonResult = jsonObject.getJSONObject("result");
            JSONArray jsonArray = jsonResult.getJSONArray("list");
            for (int i = 0; i < jsonArray.length(); i++) {

                JSONObject json = (JSONObject) jsonArray.get(i);

                CourierData data = new CourierData();

                data.setDatetime(json.getString("time"));
                data.setRemark(json.getString("status"));
                data.setZone("无");
                mList.add(data);
            }

            Collections.reverse(mList);
            CourierAdapter adapter = new CourierAdapter(this, mList);

            courier_listView.setAdapter(adapter);

        } catch (JSONException e) {
            e.printStackTrace();
        }


    }

}
